﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class cal_events : System.Web.UI.Page
{
    public string ContainerPage = "./ProcessJob.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 1000;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public string type = "";
    public string strProcessName = "";
    public int nPermissions = 0;
    public string strEvents = "";
    public string DateToday = DateTime.Now.ToString("yyyy-MM-dd");
    public string TimeToday = DateTime.Now.AddMinutes(10).ToString("HH:mm");
    public string TimeEndToday = DateTime.Now.AddHours(01).ToString("HH:mm");
    public string CustName = "";
    public int nSuperPermissions = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //loadCustormer();
            if (Session["sesNotificationRMD"] != null && Session["sesNotificationRMD"].ToString().CompareTo("1") == 0)
                cbNotifStatus.Checked = true;
            loadDropdownUser();
            //loadDropdownCustormer();
            datepicker_startdate.Text = DateToday;
            //datepicker_enddate.Text = DateToday;
            timepicker_startdate.Text = TimeToday;
            //timepicker_enddate.Text = TimeEndToday;
            if (string.IsNullOrEmpty(Request.QueryString["action"]))
            {
                LoadStepJob();
            }
            if (Request.QueryString["ID"] != null)
            {
                loadEvent();
            }
            if (Request.QueryString["PlanID"] != null)
            {
                CustomerActionPlan objplan = new CustomerActionPlan();
                objplan.ID = long.Parse(Request.QueryString["PlanID"].ToString());
                objplan.Load(GV.cn, GV.trans);
                txtName.Value = objplan.ContactDescription;
                txtDescripton.Value = objplan.ActionPlan;
            }
            if (Request.QueryString["CustID"] != null)
            {
                CustomerRelation objCust = new CustomerRelation();
                objCust.ID = long.Parse(Request.QueryString["CustID"].ToString());
                objCust.Load(GV.cn, GV.trans);
                txtCustormer.Text = objCust.Name;
            }
            if (Session["logined_id"] != null)
            {
                if (Session["superadmin"] != "") nSuperPermissions = int.Parse(Session["superadmin"].ToString());
            }
            else
                Response.Redirect("Login.aspx");
        }
    }
    protected void loadEvent()
    {
        EventInfo obj = new EventInfo();
        obj.ID = long.Parse(Request.QueryString["ID"]);
        obj.Load(GV.cn, GV.trans);
        txtName.Value = obj.Name;
        txtDescripton.Value = obj.Description;
        datepicker_startdate.Text = Convert.ToDateTime(obj.StartDate).ToString("yyyy-MM-dd");
        //datepicker_enddate.Text = Convert.ToDateTime(obj.EndDate).ToString("yyyy-MM-dd");
        timepicker_startdate.Text = Convert.ToDateTime(obj.StartDate).ToString("HH:mm");
        //timepicker_enddate.Text = Convert.ToDateTime(obj.EndDate).ToString("HH:mm");
        //drType.ClearSelection();
        //drType.SelectedValue = obj.EventType.ToString();
        //txtColor.Value = "#" + obj.ColorEV;
        //txtAlarmTime.Text = obj.AlarmTime.ToString();
        //drAlarmType.ClearSelection();
        //drAlarmType.SelectedValue = obj.AlarmType.ToString();
        string strLocation = obj.FilePath;
        if (strLocation.Length > 0)
        {
            strLocation = "<a href=\"/FormDocuments/" + strLocation + "\">Tài liệu đính kèm</a>";
            lbdownload.Text = strLocation;
        }
        drTimeUnit.ClearSelection();
        drTimeUnit.SelectedValue = obj.TimeUnit.ToString();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        if (txtName.Value == "")
        {
            strError = "NotBlank";
            strMess = "Tên sự kiện ko đc để chống!";
        }
        string strType = "";
        string strParent = "";
        EventInfo obj = new EventInfo();
        obj.ID = -1;
        if (Request.QueryString["ID"] != null)
        {
            obj.ID = long.Parse(Request.QueryString["ID"]);
            obj.Load(GV.cn, GV.trans);
        }

        if (Request.QueryString["type"] != null)
        {
            obj.EventType = int.Parse(Request.QueryString["type"].ToString());
            try
            {
                if (Session["logined_id"] != null) obj.UserID = long.Parse(Session["logined_id"].ToString());
                //if (Request.QueryString["type"].ToString() == "2")
                //{
                //    if (drAdminUser.SelectedItem.Value != null) obj.UserID = long.Parse(drAdminUser.SelectedItem.Value);
                //    obj.CustID = long.Parse(Session["logined_id"].ToString());
                //}
            }
            catch { }
            //    strType = "type=" + Request.QueryString["type"].ToString();
        }
        if (Request.QueryString["custid"] != null) obj.CustID = long.Parse(Request.QueryString["custid"]);
        obj.Name = HttpUtility.HtmlDecode(txtName.Value);
        string strStartDate = datepicker_startdate.Text + " " + timepicker_startdate.Text + ":00";
        //string strEndDate = datepicker_enddate.Text + " " + timepicker_enddate.Text + ":00";

        obj.Description = HttpUtility.HtmlDecode(txtDescripton.Value);
        //try
        //{
        //    obj.EventType = int.Parse(drType.SelectedItem.Value);
        //}
        //catch { }
        //obj.ColorEV = txtColor.Value.Replace("#", "");
        //try
        //{
        //    obj.AlarmTime = int.Parse(txtAlarmTime.Text);
        //}
        //catch { }
        //try
        //{
        //    obj.AlarmType = int.Parse(drAlarmType.SelectedItem.Value);
        //}
        //catch { }
        try
        {
            obj.TimeUnit = int.Parse(drTimeUnit.SelectedItem.Value);
        }
        catch { }
        DateTime startDate;
        DateTime endDate;
        GetTimePeriod(drTimeUnit.SelectedItem.Value, out startDate, out endDate);
        obj.StartDate = startDate;
        obj.EndDate = endDate;
        if (obj.TimeUnit == 14)
        {
            obj.StartDate = DateTime.Parse(strStartDate);
            obj.EndDate = DateTime.Parse(strStartDate).AddMonths(1);
        }
        try
        {
            string serverFileName = Path.GetFileName(FileInput.PostedFile.FileName);
            string ext = Path.GetExtension(serverFileName);
            //if (ext == ".doc" || ext == ".xls" || ext == ".docx" || ext == ".xlsx")
            {
                string strPath = MapPath(".") + "\\FormDocuments\\";
                FileInput.PostedFile.SaveAs(strPath + serverFileName);
                obj.FilePath = serverFileName;
            }
            //else
            //{
            //    strError = "File not specified";
            //    strMess = "Chỉ được upload fie wolds và exel!";
            //}

        }
        catch (Exception err)
        {
        }

        if (strError == "")
        {
            if (Request.QueryString["PlanID"] != null && Request.QueryString["PlanID"] != "")
            {
                CustomerActionPlan objPlan = new CustomerActionPlan();
                objPlan.ID = long.Parse(Request.QueryString["PlanID"].ToString());
                objPlan.Load(GV.cn, GV.trans);
                objPlan.Reminder = 1;
                objPlan.Save(GV.cn, GV.trans);
            }
            obj.Save(GV.cn, GV.trans);
            //Response.Redirect("cal_events.aspx");
        }
    }
    protected void loadDropdownUser()
    {
        string sql = "";
        DataSet ds = null;
        sql = "SELECT ID, UserName FROM tbl_adminusers ORDER BY UserName";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
        DataTable dtb = ds.Tables[0];
        drAdminUser.DataSource = dtb;
        drAdminUser.DataValueField = dtb.Columns[0].ToString();
        drAdminUser.DataTextField = dtb.Columns[1].ToString();
        drAdminUser.DataBind();
        if (Session["logined_id"] != null)
            drAdminUser.SelectedValue = Session["logined_id"].ToString();
    }
    //protected void loadDropdownCustormer()
    //{
    //    string sql = "";
    //    DataSet ds = null;
    //    sql = "SELECT ID, Name FROM tbl_customerrelation where UserID=" + Session["logined_id"].ToString() + " ORDER BY Name";
    //    ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
    //    DataTable dtb = ds.Tables[0];
    //    drCustormer.DataSource = dtb;
    //    drCustormer.DataValueField = dtb.Columns[0].ToString();
    //    drCustormer.DataTextField = dtb.Columns[1].ToString().Trim();
    //    drCustormer.DataBind();
    //    if (Session["logined_id"] != null)
    //        drCustormer.SelectedValue = Session["logined_id"].ToString();
    //}
    //public string loadCustormer()
    //{
    //    string sql = "";
    //    DataSet ds = null;
    //    sql = "SELECT Name FROM tbl_customerrelation where UserID=" + Session["logined_id"].ToString() + " ORDER BY Name";
    //    ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
    //    foreach (DataRow dr in ds.Tables[0].Rows)
    //    {
    //        CustName += dr[0].ToString();
    //    }
    //    return CustName;
    //}
    protected void LoadStepJob()
    {
        DataSet ds = null;
        int nNumOfPages = 0;
        int NumOfItemsPerPage = 100;
        int PageNo = 1;

        EventInfo obj = new EventInfo();
        strCondition = " and Status=1 and StartDate >='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
        if (Session["logined_id"] != null)
            strCondition += " and UserID=" + Session["logined_id"].ToString();
        obj.GetList(strCondition, "", "", "StartDate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);
        int count = 0;
        //rpevent.DataSource = ds.Tables[0];
        //rpevent.DataBind();
        //foreach (DataRow dr in ds.Tables[0].Rows)
        //{
        //    count++;
        //    string strName = "<a href=\"cal_events.aspx?action=update&ID=" + dr["ID"].ToString() + "\">" + dr["name"].ToString() + "</a>";
        //    strEvents += "<div class=\"event_news\">" +
        //                    "<div class=\"icon_date\">" +
        //                        "<div class=\"bold_day\">" + Convert.ToDateTime(dr["StartDate"]).ToString("MMM") + "</div>" +
        //                        "<div class=\"bold_small\">" + Convert.ToDateTime(dr["StartDate"]).ToString("dd") + "</div>" +
        //                    "</div>" +
        //                    "<div style=\"float: left; width: 300px;\">" + strName + "</div>" +
        //                "</div>";
        //}

    }

    public string GetTextColor(object colorev)
    {
        if (colorev == null || colorev.ToString() == "")
        {
            return "#000";
        }
        else
        {
            return "#fff";
        }
    }
    protected void GetTimePeriod(string timeUnit, out DateTime dateStart, out DateTime dateEnd)
    {
        string retVal = "";
        dateEnd = DateTime.Now;
        dateStart = DateTime.Now;
        int timeHours = DateTime.Now.Hour;
        int dayofweek = (int)DateTime.Now.DayOfWeek;
        int day = (int)DateTime.Now.Day;
        int month = (int)DateTime.Now.Month;

        switch (timeUnit.ToString())
        {
            case "1":
                if (timeHours >= 8 && timeHours < 10)
                {
                    dateStart = DateTime.Now;
                    dateEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateTime.Now.AddDays(1);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 10, 0, 0, 0);
                }
                break;
            case "2":
                if (timeHours >= 11 && timeHours < 13)
                {
                    dateStart = DateTime.Now;
                    dateEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateTime.Now.AddDays(1);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 11, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 13, 0, 0, 0);
                }
                break;
            case "3":
                if (timeHours >= 13 && timeHours < 15)
                {
                    dateStart = DateTime.Now;
                    dateEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateTime.Now.AddDays(1);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 13, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 15, 0, 0, 0);
                }
                break;
            case "4":
                if (timeHours >= 16 && timeHours < 18)
                {
                    dateStart = DateTime.Now;
                    dateEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateTime.Now.AddDays(1);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 16, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "5":
                //retVal = "(Đầu tuần)";
                if (dayofweek <= 2 && timeHours < 18)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentWeek();
                    dt = dt.AddDays(2);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextWeek();
                    dt = dt.AddDays(1);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddDays(1);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "6":
                //    retVal = "(Giữa tuần)";
                if (dayofweek <= 3 && timeHours < 18)
                {
                    DateTime dt = DateUtilities.GetStartOfCurrentWeek();
                    dt = dt.AddDays(3);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextWeek();
                    dt = dt.AddDays(3);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "7":
                //    retVal = "(Cuối tuần)";
                if (dayofweek >= 4 && dayofweek <= 5 && timeHours < 18)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentWeek();
                    dt = dt.AddDays(5);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextWeek();
                    dt = dt.AddDays(4);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddDays(1);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "8":
                //    retVal = "(Đầu tháng)";
                if (day >= 1 && day <= 5 && timeHours < 18)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentMonth();
                    dt = dt.AddDays(4);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextMonth();
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddDays(4);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "9":
                //    retVal = "(Giữa tháng)";
                if (day >= 13 && day <= 18)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentMonth();
                    dt = dt.AddDays(17);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextMonth();
                    dt = dt.AddDays(12);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddDays(5);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "10":
                //    retVal = "(Cuối tháng)";
                if (day >= 25 && day <= 31)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentMonth();
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextMonth();
                    dt = dt.AddDays(25);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = DateUtilities.GetEndOfNextMonth();
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "11":
                //    retVal = "(Đầu năm)";
                if (month >= 1 && month <= 3)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentYear();
                    dt = dt.AddMonths(2);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextYear();
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddMonths(2);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "12":
                //    retVal = "(Giữa năm)";
                if (month >= 5 && month <= 7)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetStartOfCurrentYear();
                    dt = dt.AddMonths(6);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextYear();
                    dt = dt.AddMonths(4);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt.AddMonths(2);
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
            case "13":
                //    retVal = "(Cuối năm)";
                if (month >= 10 && month <= 12)
                {
                    dateStart = DateTime.Now;
                    DateTime dt = DateUtilities.GetEndOfCurrentYear();
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                else
                {
                    DateTime dt = DateUtilities.GetStartOfNextYear();
                    dt = dt.AddMonths(9);
                    dateStart = new DateTime(dt.Year, dt.Month, dt.Day, 8, 0, 0, 0);
                    dt = dt = DateUtilities.GetEndOfNextYear();
                    dateEnd = new DateTime(dt.Year, dt.Month, dt.Day, 18, 0, 0, 0);
                }
                break;
        }
    }


    protected void btnSaveNote_Click(object sender, EventArgs e)
    {
        if (txtInputNote.Text.Trim().Length > 0)
        {
            strError = "";
            strMess = "";
            EventInfo obj = new EventInfo();
            obj.ID = -1;
            if (Request.QueryString["ID"] != null)
            {
                obj.ID = long.Parse(Request.QueryString["ID"]);
                obj.Load(GV.cn, GV.trans);
            }

            obj.EventType = 2;
            if (Session["logined_id"] != null) obj.UserID = long.Parse(Session["logined_id"].ToString());

            obj.Description = HttpUtility.HtmlDecode(txtInputNote.Text);
            obj.Save(GV.cn, GV.trans);
            txtInputNote.Text = "";
            Response.Redirect("cal_events.aspx?tid=3");
        }
    }
    protected void cbNotifStatus_CheckedChanged(object sender, EventArgs e)
    {
        if (cbNotifStatus.Checked)
            Session["sesNotificationRMD"] = 1;
        else
            Session["sesNotificationRMD"] = 0;
    }
}